<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-21 16:52:27
 * @LastEditTime: 2024-06-10 22:45:09
 * @FilePath: \env-manager-pc\src\views\data_query\pollute_err\components\lineChart.vue
-->
<script setup lang="ts">
import * as Echarts from 'echarts'
import dayjs from 'dayjs'
import dataQueryApi from '@/api/modules/data.query'
import { getColor } from '@/utils/index'
import { DeviceType } from '@/utils/dataHook/devices'
import useEntStore from '@/store/modules/ent'

const props = defineProps({
  isCw: {
    type: Boolean,
    default: false,
  },
  reuses: {
    type: Array,
    default: () => [],
  },
  produceData: {
    type: Object,
    default: () => ({}),
  },
  startTime: {
    type: String,
    default: '',
  },
  endTime: {
    type: String,
    default: '',
  },
  errorTime: {
    type: Array,
    default: () => ([]),
  },
})

const entStore = useEntStore()

let chart: any = null
const markId = 500
const series = ref<any>([])
const timeLine = ref<any>([])
const chartRef = ref<any>()
const title = computed(() => {
  return props.isCw ? '产污设施负荷曲线' : '治理设施负荷曲线'
})

const legends = [
  {
    name: '异常',
    class: 'danger-bg',
  },
  {
    name: '异常(已申报)',
    class: 'warn-bg',
  },
  {
    name: '检修',
    class: 'primary-bg',
  },
  {
    name: '停电',
    class: 'info-bg',
  },
]

onMounted(() => {
  nextTick(() => {
    chart = Echarts.init(chartRef.value)
    chart.setOption(getOption())
  })
  window.addEventListener('resize', () => {
    chart.resize()
  })
})

const zWdevices = computed(() => {
  if (props.isCw) {
    return []
  }
  const ElectricDevices: any = []

  props.reuses.forEach((item: any) => {
    item.ElectricDevices.forEach((elItem: any) => {
      ElectricDevices.push(elItem)
    })
  })
  return ElectricDevices
})

const markArea = computed(() => {
  const colors: any = {
    1: 'rgba(255, 153, 155, 0.4)',
    2: 'rgba(255, 255, 202, 0.4)',
    3: 'rgba(219, 239, 243, 0.4)',
    4: 'rgba(118, 122, 130, 0.4)',
  }
  return {
    data: props.errorTime.map((item: any) => {
      return [
        {
          xAxis: item.StartTime,
          itemStyle: {
            color: colors[item.Label],
          },
        },
        {
          xAxis: item.EndTime
            ? item.EndTime
            : dayjs().format('YYYY-MM-DD HH:mm:ss'),
          itemStyle: {
            color: colors[item.Label],
          },
        },
      ]
    }),
  }
})

async function refresh() {
  series.value = []
  timeLine.value = []
  await props.isCw ? getCwData() : getZlData()
  nextTick(() => {
    chart.resize()
  })
}

const maxLimit = ref<any>('dataMax')

function getOption() {
  return {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: series.value.map((item: any) => item.name),
    },
    grid: {
      left: 30,
      right: 30,
      bottom: 30,
      top: 30,
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      min: timeLine.value[0],
      axisLabel: {
        formatter(value: any) {
          // 返回自定义的时间格式
          return dayjs(value).format('HH:mm')
        },
      },
    },
    yAxis: {
      type: 'value',
      name: '单位（kW）',
      scale: true,
      nameTextStyle: {
        padding: [0, 0, 0, 60],
      },
      max: maxLimit.value,
    },
    series: series.value,
  }
}

function getZlData() {
  const zWdeviceObjIDs = zWdevices.value.map((item: any) => item.ObjID)
  return dataQueryApi.GetElectricTS({
    deviceObjIDs: zWdeviceObjIDs,
    markerIDs: [markId],
    startTime: props.startTime,
    endTime: props.endTime,
  }).then((res) => {
    const { Columns, Datas } = res as any
    timeLine.value = Columns
    const numAll: number[] = []
    series.value = zWdevices.value.map((item: any) => {
      const datas = Datas[item.ObjID]
      const color = getColor()
      const serie = {
        name: item.Name,
        type: 'line',
        symbol: 'none',
        data: datas[markId].map((value: any, index: any) => {
          numAll.push(value)
          return [
            timeLine.value[index],
            value,
          ]
        }),
        itemStyle: {
          color,
        },
        markArea: markArea.value,
        markLine: {},
      }
      if (item.PowerLimit) {
        numAll.push(item.PowerLimit)
        serie.markLine = {
          lineStyle: {
            color: 'gray', // 标线颜色
          },
          label: {
            position: 'middle',
            formatter: (params: any) => {
              const time = item.PowerDuration
                ? `(${item.PowerDuration / 60}分钟)`
                : ''
              return `${item.Name}${params.name}:${params.value}${time}`
            },
          },
          data: [
            {
              yAxis: item.PowerLimit,
            },
          ],
        }
      }
      return serie
    })
    maxLimit.value = Math.max(...numAll) + 1
    chart?.setOption(getOption())
  })
}
function getCwData() {
  const produceObjIDs = props.produceData.type === DeviceType.ReuseParts ? props.produceData.ProduceIDs : [props.produceData.ObjID]
  return dataQueryApi.GetProduceDatas({
    produceObjIDs,
    startTime: props.startTime,
    endTime: props.endTime,
  }).then((res) => {
    const { Columns, Datas } = res as any
    timeLine.value = Columns
    const numAll: number[] = []
    series.value = produceObjIDs.map((id: string) => {
      const item = entStore.currentEntData.Produces[id]
      const datas = Datas[item.ObjID]
      const color = getColor()

      const serie = {
        name: item.Name,
        type: 'line',
        symbol: 'none',
        data: datas.map((value: any, index: number) => {
          numAll.push(value)
          return [timeLine.value[index], value]
        }),
        itemStyle: {
          color,
        },
        markArea: markArea.value,
        markLine: {},
      }
      if (item.LimitLower) {
        numAll.push(item.LimitLower)
        serie.markLine = {
          lineStyle: {
            color: 'gray', // 标线颜色
          },
          label: {
            position: 'middle',
            formatter: (params: any) => {
              return `${item.Name}${params.name}:${params.value}`
            },
          },
          data: [
            {
              yAxis: item.LimitLower,
            },
          ],
        }
      }
      return serie
    })
    maxLimit.value = Math.max(...numAll) + 1
    chart?.setOption(getOption())
  })
}

defineExpose({
  refresh,
})
</script>

<template>
  <PageMain :title="title" style="margin: 10px 0;">
    <template #title>
      <div class="flex justify-between">
        {{ title }}
        <div class="legend-panel">
          <div v-for="item in legends" :key="item.name" class="legend-item">
            <div class="legend-icon" :class="item.class" />
            {{ item.name }}
          </div>
        </div>
      </div>
    </template>
    <div ref="chartRef" style="width: 100%; height: 400px;" />
  </PageMain>
</template>

<style lang="scss" scoped>
.legend-panel {
  display: flex;
  align-items: center;

  .legend-item {
    display: flex;
    align-items: center;
    margin-right: 5px;
    font-size: 12px;

    .legend-icon {
      height: 16px;
      width: 16px;
      margin-right: 10px;
    }
  }
}
</style>
